# _*_ coding utf-8 _*_
# FILENAME：.py
# DESCRIPTION: 
# AUTH: 
# DATE: 2022/6/110:56 上午


from components.BaseUploadDialog import BaseUploadDialog, BaseUpload
from constant import UploadType, UploadValidateType
from models.baseModel import get_session
from models.produceSpeedModel import ProduceSpeedDetailsModel
from utils.confUtils import read_performance_config


class UploadDialog(BaseUploadDialog):
    @staticmethod
    def get_dialog(parent=None, id=0):
        dialog = UploadDialog(parent, UploadType.PRODUCE_SPEED.value, id, Upload)
        return dialog.exec()


"""
上传类
"""


class Upload(BaseUpload):
    def save(self, sheet):
        rows = sheet.nrows  # 行
        cols = sheet.ncols  # 列

        session = get_session()

        try:
            # 分批保存数量
            bulk_save_count = read_performance_config('bulk_save_count')

            # 用于批量提交
            details_list = []

            # 删除从表数据
            session.query(ProduceSpeedDetailsModel).filter(ProduceSpeedDetailsModel.produce_speed_id == self._id).delete()

            for i in range(0, rows):
                # 从表model
                details = ProduceSpeedDetailsModel()
                details.produce_speed_id = self._id

                for c in range(0, cols):
                    value = sheet.row(i)[c].value
                    if i == 0:
                        # 检验标题是否正确
                        if (c == 0 and value != '车型') or (c == 1 and value != '生产速度') or (c == 2 and value != '节拍'):
                            raise Exception('上传文件模版错误！')
                    else:
                        if c == 0:
                            self.validate(value, [UploadValidateType.NOT_EMPTY.value], '车型', i + 1)
                            details.car_model = value
                        elif c == 1:
                            self.validate(value, [UploadValidateType.NOT_EMPTY.value, UploadValidateType.IS_NUMBER.value], '生产速度', i + 1)
                            details.produce_speed = value
                        elif c == 2:
                            self.validate(value, [UploadValidateType.NOT_EMPTY.value, UploadValidateType.IS_NUMBER.value], '节拍', i + 1)
                            details.meter = value
                        else:
                            continue

                # 保存行
                if i > 0:
                    details_list.append(details)
                    # 分批保存
                    if 0 < int(bulk_save_count) <= len(details_list):
                        # 保存
                        session.bulk_save_objects(details_list)
                        details_list = []

            # 保存
            session.bulk_save_objects(details_list)
            # 提交
            session.commit()
            session.close()
        except Exception as e:
            raise Exception(e)
        finally:
            session.close()
